package com.maibow.base.defines;

import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * 
 * @author Roy
 *
 */
public final class BeanGenerator {
	
	private final static Log logger = LogFactory.getLog(BeanGenerator.class);
	/**
	 * @alias servlet上下文
	 */
	public static ServletContext servletCtx = null;

	/**
	 * @alias spring上下文
	 */
	public static ApplicationContext applicationContext = null;

	/**
	 * Servlet上下文是否初始化完毕
	 * 
	 * @return
	 */
	public static boolean isWebApplicationContextInited() {
		return WebApplicationContextUtils.getWebApplicationContext(servletCtx) != null;
	}

	/**
	 * @alias 获取Spring应用程序上下文
	 * @return Spring应用程序上下文
	 */
	private static ApplicationContext getApplicationContext() {
		if (BeanGenerator.applicationContext != null)
			return BeanGenerator.applicationContext;
		synchronized (ApplicationContext.class) {
			if (BeanGenerator.applicationContext == null) {
				if (BeanGenerator.servletCtx != null) {
					logger.info("开始通过Servlet上下文获取spring上下文");
					BeanGenerator.applicationContext = WebApplicationContextUtils
							.getWebApplicationContext(servletCtx);
				} else {
					String springPath = "classpath:/spring/*.xml";
					logger.info("开始路径[" + springPath + "]初始化spring上下文");
					BeanGenerator.applicationContext = new ClassPathXmlApplicationContext(
							springPath);
				}
				logger.info("成功初始化spring上下文["
						+ BeanGenerator.applicationContext + "]");
				assert BeanGenerator.applicationContext != null;
			}
		}
		return BeanGenerator.applicationContext;
	}

	/**
	 * @alias 获取Bean实例
	 * @param beanName
	 *            spring中配置的bean名称
	 * @return 需要的实例对象
	 */
	public static Object getBean(String beanName) {
		return getApplicationContext().getBean(beanName);
	}

}